<script setup lang="ts">
  import { ref } from 'vue';
  import { Persistent } from '@/utils/cache/persistent';
  import { SHOW_TYPE_KEY, SN_KEY } from '@/enums/cacheEnum';
  import { RangeValue } from 'ant-design-vue/es/vc-picker/interface';
  import dayjs from 'dayjs';
  import { IotUniDataLog, selectIotUniDataLogApi } from '@/api/hc/iotDeviceData';
  import { VScroll } from '@/components/VirtualScroll';
  import Decoder from '@/views/zhm/ws/component/Decoder.vue';
  import { PageWrapper } from '@/components/Page';

  let sn = ref<string>(Persistent.getLocal(SN_KEY) || '');
  const list = ref<IotUniDataLog[]>([]);

  function snChange() {
    Persistent.setLocal(SN_KEY, sn.value);
  }

  let startTs: number = dayjs().subtract(1, 'hour').valueOf();
  let endTs: number = dayjs().valueOf();
  // let startTs: number = dayjs(1889221938000).valueOf();
  // let endTs: number = dayjs(1889224958000).valueOf();
  const onRangeChange = (dates: RangeValue<string>, dateStrings: string[]) => {
    if (dates) {
      console.log('From: ', dates[0], ', to: ', dates[1]);
      console.log('From: ', dateStrings[0], ', to: ', dateStrings[1]);
      startTs = dayjs(dateStrings[0]).valueOf();
      endTs = dayjs(dateStrings[1]).valueOf();
      console.log('From: ', startTs, ', to: ', endTs);
    } else {
      console.log('Clear');
    }
  };

  function selectIotUniDataLog() {
    selectIotUniDataLogApi({
      sn: sn.value,
      action: action.value,
      includeFields: [
        'id',
        'sn',
        'ts',
        'contents',
        'contentType',
        'protocolKey',
        'action',
        'topic',
      ],
      startTs: startTs,
      endTs: endTs,
    }).then((res) => {
      list.value = res;
    });
  }

  function coder(item: IotUniDataLog) {
    const str = item.contents;
    const uint8Array = base64ToUint8Array(str);
    switch (paramType.value) {
      case 'json':
        return String.fromCharCode.apply(String, uint8Array);
      default:
        return uint8Array;
    }
  }

  function base64ToUint8Array(base64String: string): Uint8Array {
    const padding = '='.repeat((4 - (base64String.length % 4)) % 4);
    const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');
    const rawData = window.atob(base64);
    const outputArray = new Uint8Array(rawData.length);

    for (let i = 0; i < rawData.length; ++i) {
      outputArray[i] = rawData.charCodeAt(i);
    }
    return outputArray;
  }

  const action = ref('up:set');
  const actionList = ['', 'up:set', 'up:sys', 'down:set', 'down:get'];

  const paramTypeList = ['byte', 'json'];
  const paramType = ref(Persistent.getLocal(SHOW_TYPE_KEY) || paramTypeList[0]);

  function paramTypeChange(item: string) {
    // paramType.value = item.value;
    Persistent.setLocal(SHOW_TYPE_KEY, item);
  }

  const iotUniDataLog = ref<IotUniDataLog>();

  function clickItem(item: IotUniDataLog) {
    iotUniDataLog.value = item;
  }
</script>

<template>
  <PageWrapper>
    <a-input class="w-xs mr-2" v-model:value="sn" @change="snChange" />
    <a-select v-model:value="paramType" style="width: 120px" class="mr-2" @change="paramTypeChange">
      <template v-for="item in paramTypeList" :key="item">
        <a-select-option :value="item">{{ item }}</a-select-option>
      </template>
    </a-select>
    <a-select v-model:value="action" style="width: 220px" class="mr-2">
      <template v-for="item in actionList" :key="item">
        <a-select-option :value="item">{{ item }}</a-select-option>
      </template>
    </a-select>
    <a-range-picker
      :default-value="[dayjs(startTs), dayjs(endTs)]"
      style="width: 400px"
      show-time
      format="YYYY/MM/DD HH:mm:ss"
      @change="onRangeChange"
      class="mr-2"
    />
    <a-button type="primary" @click="selectIotUniDataLog" class="mr-2">获取</a-button>
    <div class="virtual-scroll-demo-wrap mt-2">
      <VScroll :itemHeight="120" :items="list" :height="550" width="100vw" ref="vScrollRef">
        <template #default="{ item }">
          <div class="virtual-scroll-demo__item" @click="clickItem(item)">
            <div>{{ coder(item) }}</div>
            <div class="text-right mt">
              {{ dayjs(item.ts).format('YYYY-MM-DD HH:mm:ss') }}
            </div>
          </div>
        </template>
      </VScroll>
    </div>

    <Decoder :iot-uni-data-log="iotUniDataLog" />
  </PageWrapper>
</template>

<style lang="less" scoped>
  .virtual-scroll-demo {
    width: 100vw;
    height: 100vh;

    &-wrap {
      display: flex;
      justify-content: center;
      background-color: @component-background;
    }

    &__item {
      height: 120px;
      margin-top: 20px;
      padding: 0 5px;
      border-bottom: 1px solid @border-color-base;
      line-height: 20px;
      word-wrap: break-word;
    }
  }
</style>
